<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span style="font-size: 14px">更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img class="the_img" v-if="!avatar" src="../../assets/images/avatar.jpg" alt="" @click="chooseImg" />
      <img class="the_img" v-else :src="avatar" alt="" @click="chooseImg" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" accept="image/*" style="display: none" ref="iptRef" @change="onFileChange" />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadAvatar">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import user from '@/api/user'

export default {
  name: 'UserAvatar',
  components: {},
  data () {
    return {
      avatar: this.$store.state.userInfo.user_pic
    }
  },
  computed: {},
  watch: {},
  methods: {
    chooseImg () {
      // 打开文件上传
      this.$refs.iptRef.click()
    },
    onFileChange (e) {
      const files = e.target.files
      if (files.length !== 0) {
        // 1.文件转链接
        // this.avatar = URL.createObjectURL(files[0])

        // 2.文件转base64编码
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = (e) => {
          this.avatar = e.target.result
        }
      }
    },
    async uploadAvatar () {
      const { data: res } = await user.updateUserAvatar(this.avatar)
      if (res.code === 0) {
        // 更新vuex最新数据
        this.$store.dispatch('initUserInfo')
        this.$message.success(res.message)
      }
    }
  },
  created () {

  },
  mounted () {

  }
}
</script>
<style scoped>
.btn-box {
  margin-top: 10px;
}

.preview {
  object-fit: cover;
}

.the_img {
  width: 350px;
  height: 350px;
}
</style>
